<?php
/**
 * Parse Email as a contact (new or existing one)
 * 
 * 
 */

use Hive\Customizing;
use Fox\Popup;
use Fox\Generator;
use Fox\Html\DropList;
use Fox\Html\Screen;
use Hive\Ressource;
use Orx\Mailer\MailBox\Message;
$xview = Xview::instance();
$messageids = $xview->val('messageids');
$mode = $xview->val('mode');

$hasWarnings = false;
$nbContactAdded = $nbContactUpdated = 0;
	
// Warning Popup
$screen = new Screen('sParsing','parse',Msg(Hive::BUNDLE,Hive::PARSING_EXCEPTIONS_HELP,
												Customizing::instance()->applicationName()),
					true,Generator::ajaxReload('contentCol'));
$screen->buttonBarClass('text-center')
			->buttons('parse')->label(Msg(Hive::BUNDLE,Hive::PARSE_BUTTON));
if($screen->submitted()) {
	foreach($_POST as $messageIdRef => $reference) {
		$messageid = substr($messageIdRef,4);
		if(empty($messageid)) {
			continue;
		}
		try {
			$message = \Fox\Dao::load(Message::className(),$messageid);
			if($message->reference > 0) {
				continue;// Already Parsed
			}
			if(empty($reference)) {
				// Create a new contact base on message
				$contact = new Ressource();
				$name = $message->name;
				$data = array(
					'status' => Ressource::STATUS_NEW,
					'email' => $message->email,
					'creation_type' => Ressource::CREATION_TYPE_EMAIL,
					'source' => Ressource::SOURCE_EMAIL,
					//'grouping' @todo
				);
				if(!empty($name)) {
					$data = array_merge($data,Ressource::parseFullName($name));
				}
				$contact->setFields($data);
				$contact->create();
				$nbContactAdded++;
				$message->reference = $contact->getId();
				$message->reference_class_id = Ressource::MESSAGE_REFERENCE;
			} else {
				$message->reference = $reference;
				$message->reference_class_id = Ressource::MESSAGE_REFERENCE;
				$nbContactUpdated++;
			}
			// First Find If there is an existing contact 
			$message->prepareUpdate(Message::CHANGE_PARSE_CONTACT);
			$message->update();
		} catch(Fox\Object\Exception\NotExist $e) {
			continue;
		} catch(Fox\Object\Exception\Save $e) {
			Fox\Message::Error($e);
		}
	} 
} elseif(!empty($messageids)) {
		
	// Load All Messages
	$messageids = explode(':',$messageids);
	foreach($messageids as $messageid) {
		if(empty($messageid)) {
			continue;
		}
		try {
			$message = \Fox\Dao::load(Message::className(),$messageid);
			// Already Parsed
			if($message->reference > 0) {
				continue;
			}
			
			$findedInDB = \Hive\Ressource::findEmailDuplicates($message->email);
			$reference = null;
			
			if($mode == 'act-parse-as-new') {
				if(count($findedInDB) > 0) {
					$hasWarnings = true;
					// Not Possible 
					$screen->block()
							->add(new DropList('msg_'.$messageid,true))
								->blankSelectionText(Msg(Hive::BUNDLE,Hive::PARSE_AS_A_NEW_CONTACT))
								->label($message->email)
								->options($findedInDB,'ressource_id',Generator::useFunction(
								function($data) {
									return $data['first_name'].' '.$data['last_name'].' - '.$data['email'].' ['.$data['ressource_id'].']';
								}
							));
					continue;
				}
			} elseif($mode == 'act-parse-as-existing') {
				if(count($findedInDB) != 1 ) {
					$hasWarnings = true;
					$screen->block()
						->add(new DropList('msg_'.$messageid))
							->label($message->email)
							->options($findedInDB,'ressource_id',Generator::useFunction(
								function($data) {
									return $data['first_name'].' '.$data['last_name'].' - '.$data['email'].' ['.$data['ressource_id'].']';
								}
							));
					continue;
				}
				$reference = $findedInDB[0]['ressource_id'];
			} else {
				
				if(count($findedInDB) == 1 ) {
					$reference = $findedInDB[0]['ressource_id'];
				} elseif(count($findedInDB) > 1) {
					$hasWarnings = true;
					$screen->block()->add(new DropList('msg_'.$messageid,true))
							->blankSelectionText(Msg(Hive::BUNDLE,Hive::PARSE_AS_A_NEW_CONTACT))
							->label($message->email)
							->options($findedInDB,'ressource_id',Generator::useFunction(
								function($data) {
									return $data['first_name'].' '.$data['last_name'].' - '.$data['email'].' ['.$data['ressource_id'].']';
								}
							));
					continue;
				} else {
					$reference = null;
				}
			}
			if(empty($reference)) {
				// Create a new contact base on message
				$contact = new Ressource();
				$name = $message->name;
				$data = array(
					'status' => Ressource::STATUS_NEW,
					'email' => $message->email,
					'creation_type' => Ressource::CREATION_TYPE_EMAIL_EMAIL,
					'source' => Ressource::SOURCE_EMAIL
					//'grouping' @todo
				);
				if(!empty($name)) {
					$data = array_merge($data,Ressource::parseFullName($name));
				}
				$contact->setFields($data);
				$contact->create();
				$nbContactAdded++;
				$message->reference = $contact->getId();
				$message->reference_class_id = Ressource::MESSAGE_REFERENCE;
			} else {
				$message->reference = $reference;
				$message->reference_class_id = Ressource::MESSAGE_REFERENCE;
				$nbContactUpdated++;
			}
			// First Find If there is an existing contact 
			$message->prepareUpdate(Message::CHANGE_PARSE_CONTACT);
			$message->update();
		} catch(Fox\Object\Exception\NotExist $e) {
			continue;
		} catch(Fox\Object\Exception\Save $e) {
			Fox\Message::Error($e);
		}
	}
	
} else {
	return null;
}
if($nbContactAdded > 0) {
	Fox\Message::Success(Msg(Hive::BUNDLE,Hive::X_CONTACTS_HAVE_BEEN_ADDED,$nbContactAdded));
}
if($nbContactUpdated > 0) {
	Fox\Message::Success(Msg(Hive::BUNDLE,Hive::X_CONTACTS_HAVE_BEEN_UPDATED,$nbContactUpdated));
}
if($hasWarnings) {
	$popup = new Popup('pParsing',Msg(Hive::BUNDLE,Hive::PARSING_EXCEPTIONS),$screen);
	echo $popup->display();
} else {
	echo Xview::instance()->messages(true,true);
}